package com.thesis.manage.common.utils;


import org.springframework.util.Assert;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author php
 * @date 2017/12/5
 * javaBean操作类
 */
public final class BeanUtil {

    /**
     * 获取类的所有字段
     *
     * @param clazz 类
     * @return 字段数组
     */
    private static Field[] getFields(Class clazz) {
        Assert.notNull(clazz, "class can not be empty ");
        return clazz.getDeclaredFields();
    }

    /**
     * 通过字段获取对应的值
     *
     * @param field  字段名
     * @param object 类对象
     * @return fieldValue
     */
    private static Object getValueByField(Field field, Object object) {
        Assert.notNull(object, "class can not be empty ");
        Object value = null;
        try {
            field.setAccessible(true);
            value = field.get(object);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 获取对象的字段和值
     *
     * @param t   对象
     * @param <T> 泛型
     * @return 字段和值
     */
    private static <T> Map<String, Object> getMapFromObject(T t) {
        Assert.notNull(t, "class can not be empty ");
        Map<String, Object> map = new HashMap<>(16);
        Field[] fields = getFields(t.getClass());
        for (Field field : fields) {
            Object value = getValueByField(field, t);
            map.put(field.getName(), value);
        }
        return map;
    }

    /**
     * 判断对象是否为空
     *
     * @param obj 对象
     * @return boolean
     */
    private static boolean isNotEmpty(Object obj) {
        if (obj != null && !"".equals(obj)) {
            if (obj instanceof String) {
                if (((String) obj).trim().length() == 0) {
                    return Boolean.FALSE;
                }
            } else if (obj instanceof Collection) {
                if (((Collection) obj).size() == 0) {
                    return Boolean.FALSE;
                }
            } else if (obj instanceof Map && ((Map) obj).size() == 0) {
                return Boolean.FALSE;
            }
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }
}
